
// UIHaltDetectorDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "UIHaltDetector.h"
#include "UIHaltDetectorDlg.h"
#include "afxdialogex.h"
#include <string>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

std::wstring GetCurrentExePath();

#define SHELLPLUGINNAME64   L"UIHaltDetect64.dll"
#define SHELLPLUGINNAME32   L"UIHaltDetect32.dll"
#define INJECTHELPER64      L"inject-helper64.exe"
#define INJECTHELPER32      L"inject-helper32.exe"

static BOOL IsProcessBit(DWORD pid)
{
#define X86 0
#define X64 1
	typedef VOID(WINAPI* PfnGetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo);
	typedef BOOL(WINAPI* PfnIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
	PfnIsWow64Process pfnIsWow64Process = (PfnIsWow64Process)GetProcAddress(LoadLibrary(L"kernel32.dll"), "IsWow64Process");
	PfnGetNativeSystemInfo pfnGetNativeSystemInfo = (PfnGetNativeSystemInfo)GetProcAddress(LoadLibrary(L"Kernel32.dll"), "GetNativeSystemInfo");

	DWORD TargetArchitecture = X64;
	SYSTEM_INFO SystemInfo = { 0 };
	if (pfnGetNativeSystemInfo)
		pfnGetNativeSystemInfo(&SystemInfo);  //获得系统信息
	if (SystemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) //得到系统位数64
		TargetArchitecture = X64;
	else if (SystemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)//得到系统位数32
		TargetArchitecture = X86;

	if (TargetArchitecture == X86)  // 32bit system
		return FALSE;

	HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId());
	BOOL bIsWow64 = FALSE;
	BOOL bRet = TRUE;
	if (pfnIsWow64Process)
		pfnIsWow64Process(hProcess, &bIsWow64);
	CloseHandle(hProcess);
	if (bIsWow64 || !bRet)  // 32 bit
	{
		return FALSE;
	}
	return TRUE;
}

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CUIHaltDetectorDlg 对话框



CUIHaltDetectorDlg::CUIHaltDetectorDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_UIHALTDETECTOR_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CUIHaltDetectorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CUIHaltDetectorDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDOK, &CUIHaltDetectorDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDC_BUTTON1, &CUIHaltDetectorDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CUIHaltDetectorDlg::OnBnClickedButton2)
	ON_NOTIFY(NM_CLICK, IDC_SYSLINK1, OnSyslinkNotify)
END_MESSAGE_MAP()

// CUIHaltDetectorDlg 消息处理程序

BOOL CUIHaltDetectorDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	SetWindowText(L"UIHaltDetector(UI界面卡顿检测工具)");

	CEdit* pDestPid = (CEdit*)GetDlgItem(IDC_EDIT1);
	CString str;
	str.Format(L"%d", GetCurrentProcessId());
	pDestPid->SetWindowTextW(str);

	CEdit* pTimeDit = (CEdit*)GetDlgItem(IDC_EDIT2);
	pTimeDit->SetWindowTextW(L"5");

	CEdit* pWaitTimeEdit = (CEdit*)GetDlgItem(IDC_EDIT3);
	pWaitTimeEdit->SetWindowTextW(L"1500");

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	wsprintf(m_szIniPath, L"%s%s", GetCurrentExePath().c_str(), L"\\UIHaltDetector.ini");
	DeleteFileW(m_szIniPath);
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CUIHaltDetectorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CUIHaltDetectorDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CUIHaltDetectorDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CUIHaltDetectorDlg::LogToListBox(CString str)
{
	CListBox* pListBox = (CListBox*)GetDlgItem(IDC_LIST1);
	pListBox->AddString(str);
}

std::wstring GetCurrentExePath()
{
	wchar_t szPath[MAX_PATH] = { 0 };
	::GetModuleFileName(0, szPath, _countof(szPath) - 1);
	std::wstring strPath = szPath;
	size_t pos = strPath.rfind(L'\\');
	if (pos != std::wstring::npos)
		strPath = strPath.substr(0, pos);

	return strPath;
}

BOOL create_inject_process(LPCWSTR inject_helper, LPCWSTR hook_dll, DWORD id, bool bRemoteThread)
{
	BOOL success = FALSE;
	WCHAR sz_command_line[4096] = { 0 };
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFO si = { 0 };
	si.cb = sizeof(si);

	swprintf_s(sz_command_line, L"\"%s\" \"%s\" %s %lu",
		inject_helper,
		hook_dll,
		bRemoteThread ? L"0" : L"1",
		id);

	success = CreateProcessW(inject_helper, sz_command_line, NULL, NULL,
		false, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
	if (success) {
		CloseHandle(pi.hThread);
		WaitForSingleObject(pi.hProcess, 300);
		CloseHandle(pi.hProcess);
	}
	else {
		GetLastError();
	}

	return success;
}

BOOL remote_thread_inject(LPCWSTR inject_helper, LPCWSTR hook_dll, DWORD process_pid)
{
	return create_inject_process(inject_helper, hook_dll, process_pid, true);
}

void CUIHaltDetectorDlg::OnBnClickedOk()
{
	CEdit* pWaitTimeEdit = (CEdit*)GetDlgItem(IDC_EDIT3);
	CString strWaitTime;
	pWaitTimeEdit->GetWindowTextW(strWaitTime);
	WritePrivateProfileStringW(L"UIHaltDetector", L"detectTime", strWaitTime, m_szIniPath);

	CEdit* pDestPid = (CEdit*)GetDlgItem(IDC_EDIT1);
	CString str;
	pDestPid->GetWindowTextW(str);
	if (str.IsEmpty())
	{
		LogToListBox(L"目标进程ID为空.");
		return;
	}

	int dwPid = _wtoi((LPWSTR)str.GetString());
	HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPid);
	if (!hProcess)
	{
		LogToListBox(L"目标进程ID无法打开.");
		return;
	}
	CloseHandle(hProcess);

	BOOL b64BitProcess = IsProcessBit(dwPid);
	std::wstring strCurpath = GetCurrentExePath();
	std::wstring strInjectHelper = strCurpath + L"\\" + (b64BitProcess ? INJECTHELPER64 : INJECTHELPER32);
	std::wstring strInjectPlugin = strCurpath + L"\\" + (b64BitProcess ? SHELLPLUGINNAME64 : SHELLPLUGINNAME32);

	if (!remote_thread_inject(strInjectHelper.c_str(), strInjectPlugin.c_str(), dwPid))
	{
		LogToListBox(L"目标进程注入失败.");
		return;
	}
	LogToListBox(L"目标进程注入成功.");
}

void CUIHaltDetectorDlg::OnBnClickedButton1()
{
	CEdit* pTimeDit = (CEdit*)GetDlgItem(IDC_EDIT2);
	CString str;
	pTimeDit->GetWindowTextW(str);
	if (str.IsEmpty())
	{
		return;
	}

	int dwTime = _wtoi((LPWSTR)str.GetString());

	CString strTitle;
	GetWindowTextW(strTitle);
	SetWindowTextW(strTitle + L"  -- 卡顿测试中");

	HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, L"halt_lzl_event");
	WaitForSingleObject(hEvent, dwTime * 1000);
	CloseHandle(hEvent);
	SetWindowTextW(strTitle);
}

void CUIHaltDetectorDlg::OnBnClickedButton2()
{
	CListBox* pListBox = (CListBox*)GetDlgItem(IDC_LIST1);
	pListBox->ResetContent();
}

void CUIHaltDetectorDlg::OnSyslinkNotify(NMHDR* pNotifyStruct, LRESULT* result)
{
	::ShellExecute(NULL, L"open", L"https://www.ctyun.cn/developer/article/480151406186565", NULL, NULL, SW_SHOW);
	/*PNMLINK pNMLink = (PNMLINK)d_lParam;
	LITEM item = pNMLink->item;
	NMHDR hdr = pNMLink->hdr;
	if ((hdr.hwndFrom == hwnd_Link) && (item.iLink == 0))
	{
		::ShellExecute(NULL, L"open", item.szUrl, NULL, NULL, SW_SHOW);
	}
	else if (wcscmp(item.szID, L"idInfo") == 0)
	{
		::MessageBox(hDlg, L"This isn't much help.", L"Example", MB_OK);
	} */
}